
var   leadNoteLength = 0,
		fade = 0,
		fadePoint = 0,
		dev, sampleRate, lead;
		
var sourceData = new sourceDataObject();
var music = new musicObject(120, 4, sourceData);

// called from audioCallback
// inputs
// gets the next song note
// gets the song notes per beat and tempo
// outputs
// sets outgoing lead note freq and length from song note and song
// sets fadepoint for this lead note
// for a chord, we create an array of lead notes (not implemented).
function loadNote () {
		var note = music.getNextNote();

		// Reset oscillator
		lead.frequency = 0;
		lead.reset();

		// Set oscillator frequency
		lead.frequency = note.freq;
				
		// Calculate note length in samples
		leadNoteLength = Math.floor(note.dur * sampleRate * 60 * 
				music.getNotesPerBeat() / music.getTempo()
				);

		// reset fade
		fade = 0;

		// define fade point
		fadePoint = leadNoteLength - 300;
}

// audioLib calls this when the audio buffer needs filling
// plays a lead note
function audioCallback (buffer, channelCount){
		var l = buffer.length,
				sample, note, n, current;

		// loop through each sample in the buffer
		for (current=0; current<l; current+= channelCount){

				if (leadNoteLength == 0) loadNote();

				// fade in
				if (leadNoteLength > fadePoint){
						fade = 1 - (leadNoteLength-fadePoint)/300;
				// fade out
				} else if (leadNoteLength<300){
						fade = leadNoteLength/300;
				} else {
						fade = 1;
				}

				sample = 0;

				// Generate oscillator
				lead.generate();

				// Get oscillator mix and multiply by .5 to reduce amplitude
				// for a chord, we add the samples together.
				sample = lead.getMix()*0.5*fade;

				// Fill buffer for each channel
				for (n=0; n<channelCount; n++){
						buffer[current + n] = sample;
				} // for

				leadNoteLength -= 1;
		} // for 
}

// start the system
var started = 0;
function startSystem() {
		if (started == 0) {
				started = 1;
				// Create an instance of the AudioDevice class
				dev = audioLib.AudioDevice(audioCallback /* callback for the buffer fills */, 2 /* channelCount */);

				sampleRate = dev.sampleRate;

				// Create an instance of the Oscillator class... not sure what the 440 is all about - the first note?
				lead = audioLib.Oscillator(sampleRate, 440);
		} // if
}
